package net.xo68.destiny.manager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.manager.entity.SystemUser;
import net.xo68.destiny.manager.mapper.SystemUserMapper;
import net.xo68.destiny.manager.security.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;



/** 
 * SystemUser Service
 * @author wuxie(16349023@qq.com)
 * @date 2020年11月07日 16:43:18
 *
 */
@Slf4j
@Service
public class SystemUserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SystemUserMapper systemUserMapper;

    public SystemUser find(Long id) {
        return  systemUserMapper.find(id);
    }

    public SystemUser insert(SystemUser systemUser) {
        systemUser.setPassword(passwordEncoder.encode(systemUser.getPassword()));
        systemUserMapper.insert(systemUser);
        return systemUser;
    }

    public SystemUser update(SystemUser systemUser) {
        systemUserMapper.update(systemUser);
        return systemUser;
    }
    
    public int delete(Long id) {
        return systemUserMapper.delete(id);
    }
    
    public List<SystemUser> list() {
        return systemUserMapper.list();
    }
	
	public PageInfo<SystemUser> list(int pageNumber,int pageSize) {
        PageHelper.startPage(pageNumber, pageSize,true);
        List<SystemUser> docs = systemUserMapper.list();
        PageInfo<SystemUser> pageInfo = new PageInfo<SystemUser>(docs);
        return pageInfo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUser systemUser= this.systemUserMapper.findByAccount(username);
        if(systemUser==null){
            return null;
        }
        return new SecurityUser(systemUser);
    }
}